<template>
  <div></div>
</template>

<script lang="ts" setup>
import { onMounted, computed } from 'vue';
import { Message } from '@arco-design/web-vue'
import { useRoute, useRouter } from 'vue-router';
import {setToken, clearToken} from "@/utils/auth";
import { signInWx as signInWx} from '@/api/user'
import config from "@/utils/config";
const {wxredirect_uri} = config;
const route = useRoute();
const router = useRouter();

const userLoginByCode = ()=>{
  const postData = {
    wxcode : route.query.code,
  }
  try {
    signInWx(postData).then(async (res)=>{
      const {data} = res;
      const accessToken = data['X-Token']
      if(accessToken){
        setToken(accessToken)
        await router.push({name: 'Workplace'})
        Message.success(('欢迎使用系统'))
      }else{
        clearToken();
        Message.error(`ATUTH2接口异常，未正确返回token...`);
      }
    }).catch(error =>{
      throw error
    })
  }catch (err){
    clearToken();
    Message.error(err);
  }
}

onMounted(()=>{
  //解决#号问题  http://www.iraetaforging.cn:8281/report/?code=wi2OWAN8h6tOksVm7-OiTJ6aVDal89nrtfIcHjjqEW8&state=STATE#/wxcode
  const url = window.location.href
  const code = url.match(/=(\S*)&state=STATE#/)
  if (code !== null) {
    // 如果能获得code，说明需要处理url并跳转，如果不能获得code，不用处理
    const replaceUrl = wxredirect_uri + '?code=' + code[1] + '&state=STATE'
    return window.location.replace(replaceUrl)
  } else {
    userLoginByCode()
  }
})
</script>

<style scoped>

</style>
